using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.Entity.DomainModels;
using SqlSugar;

namespace VOL.demo.Repositories
{
    public partial class PurchaseOrderModelRepository
    {
        /// <summary>
        /// 分页查询进货订单（带关联查询和计算字段）
        /// </summary>
        public async Task<(List<PurchaseOrderModel> Data, int TotalCount)> GetPurchaseOrderPageListAsync(
            int pageIndex, 
            int pageSize, 
            string orderCode = null, 
            int? status = null, 
            long? supplierId = null, 
            DateTime? orderDate = null)
        {
            // 先查询主表数据
            var query = DbContext.Queryable<PurchaseOrderModel>()
                .LeftJoin<suppliermodel>((po, s) => po.SupplierId == s.Id)
                .LeftJoin<Sys_User>((po, s, u) => po.UserId == u.User_Id)
                .LeftJoin<Sys_Department>((po, s, u, d) => po.DeptId == SqlFunc.ToString(d.DepartmentId))
                .Where((po, s, u, d) => po.IsDel == 0)
                .WhereIF(!string.IsNullOrEmpty(orderCode), (po, s, u, d) => po.OrderCode.Contains(orderCode))
                .WhereIF(status.HasValue, (po, s, u, d) => po.Status == status)
                .WhereIF(supplierId.HasValue, (po, s, u, d) => po.SupplierId == supplierId)
                .WhereIF(orderDate.HasValue, (po, s, u, d) => po.OrderDate.Value.Date == orderDate.Value.Date)
                .Select((po, s, u, d) => new PurchaseOrderModel
                {
                    Id = po.Id,
                    OrderCode = po.OrderCode,
                    OrderDate = po.OrderDate,
                    SupplierId = po.SupplierId,
                    Contact = po.Contact,
                    ContactPhone = po.ContactPhone,
                    DeptId = po.DeptId,
                    UserId = po.UserId,
                    Status = po.Status,
                    AuditUser = po.AuditUser,
                    AuditTime = po.AuditTime,
                    Remarks = po.Remarks,
                    Creator = po.Creator,
                    CreateDate = po.CreateDate,
                    Modifier = po.Modifier,
                    ModifyDate = po.ModifyDate,
                    CreateID = po.CreateID,
                    ModifyID = po.ModifyID,
                    SupplierName = s.SupplierName,
                    UserName = u.UserTrueName,
                    DeptName = d.DepartmentName,
                    StatusName = po.Status == 1 ? "草稿" :
                                po.Status == 2 ? "待审核" :
                                po.Status == 3 ? "驳回" :
                                po.Status == 4 ? "未入库" :
                                po.Status == 5 ? "部分入库" :
                                po.Status == 6 ? "已完成" : "未知"
                })
                .OrderByDescending(po => po.CreateDate);

            // 使用 ToPageList 方法同时获取总数和分页数据（更可靠）
            RefAsync<int> totalCount = 0;
            var data = await query.ToPageListAsync(pageIndex, pageSize, totalCount);

            // 为每个订单计算汇总数据
            foreach (var item in data)
            {
                try
                {
                    // 获取明细数据并计算汇总
                    var details = await DbContext.Queryable<PurchaseOrderItemModel>()
                        .Where(poi => poi.OrderCode == item.OrderCode && poi.IsDel == 0)
                        .ToListAsync();

                    item.TotalQuantity = details.Sum(d => d.PurchaseQty ?? 0);
                    item.TotalAmount = details.Sum(d => (d.PurchaseQty ?? 0) * (d.PurchasePrice ?? 0));
                    
                    // 处理进货货品字段，限制显示长度
                    var goods = details.Select(d => d.GoodsName).Where(g => !string.IsNullOrEmpty(g)).Distinct().ToList();
                    
                    // 调试日志：记录明细数据
                    Console.WriteLine($"订单 {item.OrderCode} 的明细数量: {details.Count}, 货品名称: {string.Join(",", goods)}");
                    
                    if (goods.Count > 3)
                    {
                        item.PurchaseGoods = string.Join("、", goods.Take(3)) + $"等{goods.Count}项.......";
                    }
                    else
                    {
                        item.PurchaseGoods = string.Join("、", goods);
                    }
                }
                catch (Exception ex)
                {
                    // 如果明细表查询失败，设置默认值
                    item.TotalQuantity = 0;
                    item.TotalAmount = 0;
                    item.PurchaseGoods = "明细数据查询失败";
                    
                    // 记录错误日志（可选）
                    // Logger.LogError($"查询进货单明细失败: {ex.Message}");
                }
            }

            return (data, totalCount.Value);
        }
    }
}
